package com.mantru.iotpot.Home;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;


import com.mantru.iotpot.ApplicationClass;
import com.mantru.iotpot.DateClass.FoodList;
import com.mantru.iotpot.R;
import com.mantru.iotpot.Util.ToastUtils;
import com.wefika.flowlayout.FlowLayout;


import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends AppCompatActivity implements View.OnClickListener {
    private boolean isAlphabetSelectorVisible = false;
    private FrameLayout alphabet;
    private Button button1;
    private Button button2;
    private EditText editText;
    private FlowLayout recentItemsContainer;
    private List<String> recentSearches = new ArrayList<>();
    private ApplicationClass ac;
    private int count = 100000;//菜单
    private int count1 = 10;//最近搜索
    private List<FoodList> vegetableList = new ArrayList<>();
    private ImageView clean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main7);
        ac = (ApplicationClass) getApplication();// 初始化 ApplicationClass
        GridView gridView = findViewById(R.id.search_gridView);
        initializeGridView(0,"","");//加载GridView的方法

        alphabet = findViewById(R.id.alphabet_selector_container);
        button1 = findViewById(R.id.search_button1);
        button2 = findViewById(R.id.search_button2);
        editText = findViewById(R.id.searchEditText);
        recentItemsContainer = findViewById(R.id.recentItemsContainer);
        clean = findViewById(R.id.searchClean);//清除输入框内容
        loadRecentSearches();// 加载最近使用的搜索记录
        // 添加 TextWatcher 监听
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // 文本变化前的回调
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // 文本变化中的回调
            }
            @Override
            public void afterTextChanged(Editable s) {
                // 文本变化后的回调
                if (s.length() > 0) {
                    clean.setVisibility(View.VISIBLE); // 如果有输入内容，显示清除图标
                } else {
                    clean.setVisibility(View.GONE); // 如果没有输入内容，隐藏清除图标
                }
            }
        });
        findViewById(R.id.searchButton).setOnClickListener(this);
        findViewById(R.id.cancelTextView).setOnClickListener(this);
        button1.setOnClickListener(this);
        button2.setOnClickListener(this);
        editText.setOnClickListener(this);
        clean.setOnClickListener(this);
        editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                // 检查是否是按下 Enter 键或者完成操作
                if ((event != null && (event.getAction() == KeyEvent.ACTION_DOWN) && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))
                        || actionId == EditorInfo.IME_ACTION_DONE
                        || actionId == EditorInfo.IME_ACTION_NEXT
                        || actionId == EditorInfo.IME_ACTION_SEND) {
                    // 获取输入法管理器
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    // 隐藏软键盘
                    if (imm != null) {
                        imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                    }
                    return true;
                }
                return false;
            }
        });
    }
    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.search_button1){//点击综合排序
            alphabet.setVisibility(View.GONE);
            button1.setBackgroundResource(R.drawable.button8);//颜色切换为选中的样式
            button2.setBackgroundResource(R.drawable.button7);//颜色切换为未选中的样式
            GridView gridView = findViewById(R.id.search_gridView);//更新gridView
            initializeGridView(0,"","");//加载GridView的方法
        } else if (v.getId() == R.id.search_button2) {//点击首字母排序
            showAlphabetSelector();
            alphabet.setVisibility(View.VISIBLE);
            button2.setBackgroundResource(R.drawable.button8);//颜色切换为选中的样式
            button1.setBackgroundResource(R.drawable.button7);//颜色切换为未选中的样式
            GridView gridView = findViewById(R.id.search_gridView);//更新gridView
            initializeGridView(2,"A","");//加载GridView的方法
        }else if (v.getId() == R.id.searchButton) {//点击搜索图标
            // 搜索框的搜索按钮点击事件
            String searchText = editText.getText().toString();
            if (!searchText.isEmpty()) {
                performSearch(searchText);
            }
        } else if (v.getId() == R.id.cancelTextView){
            finish();
        } else if (v.getId() == R.id.searchClean) {
            editText.setText("");//将输入框内容清空
            clean.setVisibility(View.GONE);
            // 加载所有商品
            initializeGridView(0, "", "");
            // 更新最近搜索记录的UI
            updateRecentSearchesUI();
        }
    }
    //加载字母选择条
    private void showAlphabetSelector() {
        alphabet.removeAllViews(); // 清除之前的视图
        LinearLayout alphabetSelector = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.alphabet_selector, null);
        // 动态生成字母按钮
        for (char c = 'A'; c <= 'Z'; c++) {
            // 加载 letter_button.xml 文件
            Button letterButton = (Button) LayoutInflater.from(this).inflate(R.layout.alphabet_button1, alphabetSelector, false);
            letterButton.setText(String.valueOf(c)); // 设置按钮文本
            letterButton.setTextSize(18); // 设置字体大小
            letterButton.setLayoutParams(new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    1.0f // 均匀分布
            ));
            letterButton.setOnClickListener(v -> {
                // 获取当前选中的字母按钮
                Button selectedButton = (Button) v;
                // 遍历所有子视图，重置它们的背景
                for (int i = 0; i < alphabetSelector.getChildCount(); i++) {
                    View child = alphabetSelector.getChildAt(i);
                    if (child instanceof Button) {
                        Button btn = (Button) child;
                        if (btn == selectedButton) {
                            // 将选中的按钮背景设置为 R.drawable.button17
                            btn.setBackgroundResource(R.drawable.button17);
                        } else {
                            // 将其他按钮背景设置为 R.drawable.button10
                            btn.setBackgroundResource(R.drawable.button10);
                        }
                    }
                }
                String selectedLetter = selectedButton.getText().toString(); // 获取选择的字母
                //Toast.makeText(this, "选择字母: " + selectedLetter, Toast.LENGTH_SHORT).show();
                ToastUtils.show(this, "选择字母: " + selectedLetter);
                initializeGridView(2, selectedLetter, ""); // 加载GridView的方法
            });
            alphabetSelector.addView(letterButton); // 添加按钮到字母选择条
        }
        // 将字母选择条添加到容器中
        alphabet.addView(alphabetSelector);
        alphabet.setVisibility(View.VISIBLE);
        // 默认选中字母 "A"
        if (alphabetSelector.getChildCount() > 0) {
            Button firstButton = (Button) alphabetSelector.getChildAt(0);
            firstButton.performClick();
        }
    }
    // 加载最近搜索记录
    private void loadRecentSearches() {
        String json_data = ac.GetSQLData_Vegetable_Search_GetText(count1);
        Log.d("SearchActivity","json_data: " + json_data);
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            boolean success = jsonObject.getBoolean("success");
            if (success) {
                JSONArray itemDataArray = jsonObject.getJSONArray("item_data");
                for (int i = 0; i < itemDataArray.length(); i++) {
                    JSONObject vegetableJson = itemDataArray.getJSONObject(i);
                    String item_data = vegetableJson.getString("text");
                    recentSearches.add(item_data); // 将搜索记录添加到列表中
                }
                updateRecentSearchesUI(); // 更新UI
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // 更新最近搜索记录的UI
    private void updateRecentSearchesUI() {
        recentItemsContainer.removeAllViews();
        for (String search : recentSearches) {
            // 加载recent_search_item布局文件
            View itemView = LayoutInflater.from(this).inflate(R.layout.searchtext, null);
            TextView textView = itemView.findViewById(R.id.search_text1);
            textView.setText(search);
            // 设置布局参数，确保每个条目自适应排列
            FlowLayout.LayoutParams params = new FlowLayout.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            params.setMargins(8, 8, 8, 8); // 添加间距
            textView.setLayoutParams(params);
            // 为每个搜索记录设置点击事件
            itemView.setOnClickListener(v -> {
                // 将选中的搜索记录内容填充到搜索框
                editText.setText(search);
                // 触发搜索功能
                performSearch(search);
            });
            recentItemsContainer.addView(itemView);
        }
    }
    //用于读取json数据并且将数据加载到GridView中的方法
    private void initializeGridView(int type,String letter,String seach) {
        vegetableList.clear();// 清空vegetableList列表
        // 获取 JSON 数据
        String json_data = "";//初始化
        if (type == 1){//搜索
            json_data = ac.GetSQLData_Vegetable_Search(type, seach, count,"");
            Log.d("搜索","搜索：" + json_data);
        }else if (type == 2){//首字母排序
            json_data = ac.GetSQLData_Vegetable_Search(type, "", count,letter);
            Log.d("首字母排序","首字母排序：" + json_data);
        } else if (type == 0) {//综合排序
            json_data = ac.GetSQLData_Vegetable_List(count);
        }
        // 解析 JSON 数据
        try {
            JSONObject jsonObject = new JSONObject(json_data);
            boolean success = jsonObject.getBoolean("success");
            if (success) {
                JSONArray itemDataArray = jsonObject.getJSONArray("item_data");
                for (int i = 0; i < itemDataArray.length(); i++) {
                    JSONObject vegetableJson = itemDataArray.getJSONObject(i);
                    String vegetableId = vegetableJson.getString("vegetable_id");
                    String vegetableName = vegetableJson.getString("vegetable_name");
                    String faceImageUrl = vegetableJson.getString("face_image_url");
                    faceImageUrl = faceImageUrl.replace("file:///", "");
                    Log.d("tupian", "lujing" + "  " + faceImageUrl);
                    // 添加到列表
                    vegetableList.add(new FoodList(vegetableId, vegetableName, faceImageUrl));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置 GridView 适配器
        GridAdapter adapter = new GridAdapter(this, vegetableList);
        GridView gridView = findViewById(R.id.search_gridView);
        gridView.setAdapter(adapter);
        gridView.setNumColumns(3); // 设置为3列
    }

    //用于处理搜索逻辑
    private void performSearch(String searchText) {
        // 隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
        }
        // 检查是否已经存在该搜索记录，如果存在则移除旧的记录
        if (recentSearches.contains(searchText)) {
            recentSearches.remove(searchText);
        }
        // 将新的搜索记录添加到列表开头
        recentSearches.add(0, searchText);
        // 限制最近搜索记录的数量，例如最多保存10条
        if (recentSearches.size() > 10) {
            recentSearches.remove(recentSearches.size() - 1);
        }
        updateRecentSearchesUI(); // 更新UI
        // 加载搜索结果
        initializeGridView(1, "", searchText);
    }
}